package br.com.amigooo.controller;

import static br.com.caelum.vraptor.view.Results.json;

import java.util.Date;

import br.com.amigooo.Session.UserSession;
import br.com.amigooo.model.AccessRequest;
import br.com.amigooo.model.ReturnMessage;
import br.com.amigooo.model.User;
import br.com.amigooo.repository.AccessRequestImpl;
import br.com.amigooo.repository.UserImpl;
import br.com.amigooo.util.Utils;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class UserController {
	private Result result;
    private UserSession userSession;
    private ReturnMessage returnMessage;
    
    public UserController(Result result, UserSession userSession) {
        this.result = result;
        this.userSession = userSession;
	}

    @Path("/activeuser/requeststatus")
	@Get
	public void requestStatus(Integer id){
    	
    	AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
    	
    	if(id != null && !"".equals(id)){
    		try{
    			AccessRequest accessRequest = accessRequestImpl.getAccessRequest(id);
    			this.returnMessage = new ReturnMessage(accessRequest.getStatus().toString(), null, "Status");
    		}catch(Exception e){
    			e.printStackTrace();
    			this.returnMessage = new ReturnMessage("error", null, "error");
    		}
    	}else{
    		this.returnMessage = new ReturnMessage("error", null, "error");
    	}
    	result.use(json()).from(this.returnMessage).serialize();
    }
    
    @Path("/activeuser/cancelaccess")
	@Get
	public void denyAccess(Integer id){
		AccessRequest accessRequest = new AccessRequest();
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		try{
			if(id != null){
				accessRequest = accessRequestImpl.getAccessRequest(id);
				
				if(accessRequest != null && accessRequest.getId() != null && (accessRequest.getStatus() == 1 || accessRequest.getStatus() == 0)){
					accessRequest.setStatus(3);
					accessRequestImpl.update(accessRequest);
					
					this.returnMessage = new ReturnMessage(accessRequest.getId().toString(), null, "Usuário cancelado.");
				}else{
					this.returnMessage = new ReturnMessage("erro", "Usuário não está na lista, foi aceito ou cancelado.", null);
				}
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			result.include("error", Utils.message("Ocorreu um erro ao liberar o acesso.", Utils.ERROR));
			result.use(json()).from(this.returnMessage).serialize();
		}
		
		result.use(json()).from(this.returnMessage).serialize();
	}    
    
    @Path("/activeuser/newrequest")
	@Get
	public void requestAccess(User user, Integer establishment, String observation){
		UserImpl userImpl = new UserImpl();
		AccessRequestImpl accessRequestImpl = new AccessRequestImpl();
		
		AccessRequest accessRequest = new AccessRequest();
		
		accessRequest.setDateRequest(new Date());
		accessRequest.setEstablishment(establishment);
		accessRequest.setObservation(observation);
		accessRequest.setStatus(1);
		
		try{
			
			if(accessRequestImpl.getActiveAccessByCompanyBoth(establishment).size() > 0 ){
				AccessRequest ac = new AccessRequest();
				
				ac = accessRequestImpl.getAccessByUser(user.getEmail());
				
				if(ac == null){
					user = userImpl.getUser(user.getEmail());
					accessRequest.setUser(user);
					accessRequest = accessRequestImpl.save(accessRequest);

					this.returnMessage = new ReturnMessage(accessRequest.getId().toString(), null, "Usuário adicionado");
				}else{
					this.returnMessage = new ReturnMessage("erro", "O usuário já foi adicionado ou está ativa", null);
				}
			}else{
				user = userImpl.getUser(user.getEmail());
				accessRequest.setUser(user);
				accessRequest = accessRequestImpl.save(accessRequest);
				this.returnMessage = new ReturnMessage(accessRequest.getId().toString(), null, "Usuário adicionado");
			}
		}catch(RuntimeException e){
			e.printStackTrace();
			this.returnMessage = new ReturnMessage("erro", "Ocorreu um erro ao adicionar o usuário " + e.getMessage(), null);
			result.use(json()).from(this.returnMessage).serialize();
		}
		
		result.use(json()).from(this.returnMessage).serialize();
	}
}